<?php

/**
 * Element de parsing pour les tags de la forme {$...} ou {$$...}
 *
 * @category   McCube
 * @package    Template\Parser\Element
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 */
class McCube_Template_Parser_Element_Variable
    extends McCube_Template_Parser_Abstract{

    /**
     * Parses a string to find the items to variable
     *
     * @param string $string
     * @return string
     */
    public function parse($string){
        $string = $this->_parseTag('.*', $string);
        return $string;
    }

    /**
     *
     *
     * @param array $matches
     * @return string
     */
    protected function _parseCallback($matches){
        $inTag = parent::_stripSlashes($matches['inTag']);

        $objName     = 'McCube_Template_Parser_Element_Variable_Version1';
        $objInstance = new $objName($this);
        return $objInstance->{$matches['execution'] ? 'execution' : 'build'}(
              $matches['variable']
            , $inTag
        );
    }

    /**
     *
     *
     * @param string $tag
     * @return string
     */
    protected function _getPattern($tag){
        return '~(?<!\\\)'
            .McCube_Template_Parser::$delimiters[0]
                .'(?<execution>[\$]{0,1})'
                .'(?<type>\$)(?<variable>.[^|}]*)'
                .'(?<inTag>.*?)'
            .'(?<!\\\)'.McCube_Template_Parser::$delimiters[1]
            .'~'
        ;
    }

    /**
     *
     *
     * @param string $tag
     * @param string $string
     * @param string $type
     * @return string
     */
    protected function _parseTag($tag, $string, $type='$'){
        return preg_replace_callback(
              $this->_getPattern($tag)
            , array($this, '_parseCallback')
            , $string
        );
    }
}